package members

import (
	"net/http"
	"strings"
	"time"
	"adai.design/homeserver/log"
	"github.com/gorilla/websocket"
)

var router = map[string]http.Handler{}

type routerHTTP struct {}

func (*routerHTTP) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	request.ParseForm()
	log.Debug("path: %v", request.URL.Path)
	path := strings.Split(request.URL.Path, "/")
	if h, ok := router[path[1]]; ok {
		h.ServeHTTP(response, request)
		return
	}
	http.Error(response, "404 Not Found", 404)
}

func Start(end chan bool) {
	go func() {
		serveHTTP := http.Server{
			Addr: ":6667",
			Handler: &routerHTTP{},
			ReadTimeout: 5 * time.Second,
		}

		// websocket长连接服务
		//workers = &receptions{
		//	end: end,
		//	upgrader: websocket.Upgrader{},
		//	address: serveHTTP.Addr,
		//}

		workers.end = end
		workers.upgrader = websocket.Upgrader{}
		workers.address = serveHTTP.Addr

		router["membership"] = workers
		go workers.start()

		// http服务 包含 websocket长连接和普通的http资源获取
		// 部署在同一端口
		//err := serveHTTP.ListenAndServeTLS("conf/214196856420593.pem", "conf/214196856420593.key")
		err := serveHTTP.ListenAndServe()

		if err != nil {
			log.Error("listen and serve: %s", err)
		}
		end <- true
	}()
}





















